package com.example.myproject.controller;

import com.example.myproject.model.CustomUserDetails;
import com.example.myproject.model.User;
import com.example.myproject.service.UserService;
import com.example.myproject.service.EmailService;
import com.example.myproject.utils.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;

    @Autowired
    private AuthenticationManager authenticationManager;

    //登录器与原来完全不同
    @PostMapping("/login")
    public Result<CustomUserDetails> loginController(@RequestParam String username, @RequestParam String password) {
        try {
            // 使用Spring Security的AuthenticationManager来进行认证
            Authentication authentication = authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(username, password)
            );
            // 认证成功后，将Authentication对象设置到SecurityContextHolder中
            SecurityContextHolder.getContext().setAuthentication(authentication);

            // 获取当前用户的详细信息
            CustomUserDetails userDetails = (CustomUserDetails) authentication.getPrincipal();
            System.out.println("Login successful for user: " + username);
            System.out.println("User authorities: " + userDetails.getAuthorities());
            return Result.success(userDetails);
        } catch (AuthenticationException e) {
            return Result.error("401", "登录失败：" + e.getMessage());
        }
    }





    @PostMapping("/register")
    public Result registerController(@RequestBody User newUser) {
        if (userService.checkEmailExists(newUser.getEmail())) {
            return Result.error("邮箱冲突", "邮箱已被使用，请使用其他邮箱注册或找回密码！");
        }
        boolean success = userService.preRegisterUser(newUser);
        if (success) {
            // 可以考虑返回一个基本的成功信息，或者创建一个没有敏感信息的User对象
            User responseUser = new User();
            responseUser.setEmail(newUser.getEmail());  // 仅返回用户的电子邮箱
            return Result.success(responseUser, "验证邮件已发送，请检查您的邮箱。");
        } else {
            return Result.error("注册失败", "用户名已存在或注册失败！");
        }
    }
    public static class VerificationRequest {
        private String email;
        private String code;

        // Getters and setters
        public String getEmail() {
            return email;
        }

        public void setEmail(String email) {
            this.email = email;
        }

        public String getCode() {
            return code;
        }

        public void setCode(String code) {
            this.code = code;
        }
    }

    @GetMapping("/get")
    public Result<List<User>> getAllUsers() {
        List<User> users = userService.getAllUsers();
        return Result.success(users, "查找所有用户成功！");
    }

    @PostMapping("/verify-code")
    public Result verifyEmailCode(@RequestBody VerificationRequest verificationRequest) {
        String email = verificationRequest.getEmail();
        String code = verificationRequest.getCode();
        boolean isVerified = userService.verifyEmail(email, code);
        if (isVerified) {
            return Result.success(null, "邮箱验证成功！");
        } else {
            return Result.error("验证失败", "验证码错误或已过期！");
        }
    }

    @PostMapping("/add")
    public Result<User> addUser(@RequestParam String username, @RequestParam String password, @RequestParam String confirmPassword, @RequestParam String email) {
        try {
            if (!password.equals(confirmPassword)) {
                return Result.error("123", "密码和确认密码不一致！");
            }

            User newUser = userService.addUser(username, password, email);
            return Result.success(newUser, "添加成功！");
        } catch (Exception e) {
            return Result.error("500", e.getMessage());
        }
    }
    @GetMapping("/search/{username}")
    public Result<User> getUserByUsername(@PathVariable String username) {
        User user = userService.getUserByUsername(username);
        if (user != null) {
            return Result.success(user, "查询成功！");
        } else {
            return Result.error("404", "用户不存在！");
        }
    }
    @PutMapping("/edit/{username}")
    public Result<User> updateUserByUsername(@PathVariable String username, @RequestBody User userDetails) {
        try {
            User updatedUser = userService.updateUserByUsername(username, userDetails);
            return Result.success(updatedUser, "更新成功！");
        } catch (Exception e) {
            return Result.error("500", e.getMessage());
        }
    }
    @DeleteMapping("/delete/{username}")
    public Result<String> deleteUserByUsername(@PathVariable String username) {
        try {
            userService.deleteUserByUsername(username);
            System.out.println("Received request to delete user: " + username); // 打印接收到的用户名
            return Result.success("删除成功！");

        } catch (Exception e) {
            return Result.error("500", e.getMessage());
        }
    }
    @GetMapping("/search")
    public Result<List<User>> searchUsers(@RequestParam String username) {
        List<User> users = userService.searchUsersByUsername(username);
        return Result.success(users, "查询成功！");
    }
}
